<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/1/2
  Time: 17:41
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%@ page language="java" import="com.ssm.utils.*" %>
<%@ taglib prefix= "c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>

<head>
    <%
        pageContext.setAttribute("APP_PATH",request.getContextPath());

    %>
    <link href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script type = "text/javascript" src ="${APP_PATH}/static/js/jquery-3.2.1.js"></script>
    <script type = "text/javascript" src = "${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <title>员工列表</title>
</head>
<body>

<div class = "container">
    <!-- 显示标题 -->
    <div class = "row">
        <div class = "col-md-12">
            <h1>员工信息</h1>
        </div>
    </div>
    <!-- 显示按钮 -->
    <div class = "row">
        <div class="col-md-2 col-md-offset-10">
            <button class = "btn btn-primary" data-toggle="modal" id = "addEmpBtn">新增</button>
            <button class = "btn btn-danger" data-toggle="modal" id = "delEmpBtn">删除</button>
        </div>
    </div>

    <!--员工添加 Modal -->
    <div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" >员工添加</h4>
                </div>
                <div class="modal-body">
                <%-- 表单 --%>
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label  class="col-sm-2 control-label">姓名</label>
                            <div class="col-sm-10 has-feedback">
                                <input type="text" class="form-control" name = "empName" id="empName_input" placeholder="用户名6-16位由数字和字母构成，或者由2-5位汉字构成">
                                <span class="form-control-feedback" aria-hidden="true"></span>
                                <span class="help-block"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <label  class="col-sm-2 control-label">邮箱</label>
                            <div class="col-sm-10 has-feedback">
                                <input type="email" class="form-control" id="email_input" name = "email" placeholder="@sina.com">
                                <span class="form-control-feedback" aria-hidden="true"></span>
                                <span class="help-block"></span>
                            </div>
                        </div>

                        <%-- 性别单选框 --%>
                        <div class="form-group">
                            <label  class="col-sm-2 control-label">性别</label>
                            <div class="col-sm-10">
                                <label class="radio-inline">
                                    <input type="radio" name="gender" id="m_radio" value="M" checked = "checked"> 男
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="gender" id="f_radio" value="F"> 女
                                </label>
                            </div>
                        </div>

                        <%-- 部门下拉框 --%>
                        <div class="form-group">
                            <label  class="col-sm-2 control-label">部门</label>
                            <div class="col-sm-4">
                                <select class="form-control" id = "dept_select" name = "dId">
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id = "saveEmployee_btn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!--员工修改 Modal -->
    <div class="modal fade" id="updateEmpModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">员工添加</h4>
                </div>
                <div class="modal-body">
                    <%-- 表单 --%>
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label  class="col-sm-2 control-label">姓名</label>
                            <div class="col-sm-10 has-feedback">
                                <p class="form-control-static" id = "updateEmp_p"></p>
                            </div>
                        </div>
                        <div class="form-group">
                            <label  class="col-sm-2 control-label">邮箱</label>
                            <div class="col-sm-10 has-feedback">
                                <input type="email" class="form-control" id="email_update_input" name = "email" placeholder="@sina.com">
                                <span class="form-control-feedback" aria-hidden="true"></span>
                                <span class="help-block"></span>
                            </div>
                        </div>

                        <%-- 性别单选框 --%>
                        <div class="form-group">
                            <label  class="col-sm-2 control-label">性别</label>
                            <div class="col-sm-10">
                                <label class="radio-inline">
                                    <input type="radio" name="gender" id="m_update_radio" value="M" checked = "checked"> 男
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="gender" id="f_update_radio" value="F"> 女
                                </label>
                            </div>
                        </div>

                        <%-- 部门下拉框 --%>
                        <div class="form-group">
                            <label  class="col-sm-2 control-label">部门</label>
                            <div class="col-sm-4">
                                <select class="form-control" id = "dept_update_select" name = "dId">
                                </select>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id = "updateEmployee_btn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 表格主体部分-->
    <div class = "row">
        <table class = "table table-hover" id = "empTable">
            <thead>
                <tr>
                    <th><input type = "checkbox" id = "checkAll"/></th>
                    <th>员工号</th>
                    <th>姓名</th>
                    <th>性别</th>
                    <th>电子邮箱</th>
                    <th>部门号</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
    <!-- 分页 -->
    <div class = "row">
        <div class = "col-md-6" id = "pageInfo"></div>
        <div class="col-md-6" id = "navInfo"></div>
    </div>
</div>

<script type = "text/javascript">

    var totalPage;//总页数
    var currentPage;//当前页
    var pageSize; //每页大小

    $(function(){
       goToPage(1);
    });
    
    //点击按钮跳转到相应的页码
    function goToPage(pageNum) {
        $.ajax({
            url : "${APP_PATH}/getEmpToJSON",
            data : "pageNum=" + pageNum,
            type : "GET",
            success:function(result){
                //console.log(result);
                //解析员工信息
                build_emps(result);
                //解析分页信息
                buildPageInfo(result);
                //解析导航条信息
                buildNav(result);
            }
        });
    }

    //解析员工信息
    function build_emps(result) {
        $("#empTable tbody").empty();
        var emps = result.extendMap.pageInfo.list;
        $.each(emps,function (index,item) {
            var checkboxTd = $("<td><input type = 'checkbox' class = 'check-item'></td>");
            var empIdTd = $("<td></td>").append(item.empId).addClass("emp-id");
            var empNameTd = $("<td></td>").append(item.empName).addClass("emp-name");
            var gender = item.gender == 'M' ? "男" : "女";
            var genderTd = $("<td></td>").append(gender);
            var emailTd = $("<td></td>").append(item.email);
            var deptNameTd = $("<td></td>").append(item.department.deptName);

            var editBtn = $("<button></button>").addClass("btn btn-info btn-primary btn-sm update-btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("编辑");

            //编辑按钮附加一个员工id的属性
            editBtn.attr("empId",item.empId);

            var delBtn = $("<button></button>").addClass("btn btn-danger btn-primary btn-sm delete-btn")
                .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除");
            delBtn.attr("empId",item.empId); //将员工id附加到按钮的属性上

            var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn);

            $("<tr></tr>").append(checkboxTd)
                .append(empIdTd)
                .append(empNameTd)
                .append(genderTd)
                .append(emailTd)
                .append(deptNameTd)
                .append(btnTd)
                .appendTo("#empTable tbody");
        });

        totalPage = result.extendMap.pageInfo.total;
        currentPage = result.extendMap.pageInfo.pageNum;
        pageSize = result.extendMap.pageInfo.pageSize;
    }

    //解析页数信息
    function buildPageInfo(result) {
        $("#pageInfo").empty(); //发送请求之前先清空
        $("#pageInfo").append("当前 " + result.extendMap.pageInfo.pageNum  + "/总页数 " + result.extendMap.pageInfo.pages);
    }

    //解析分页条
    function buildNav(result) {
        $("#navInfo").empty();
        var ul = $("<ul></ul>").addClass("pagination");
        var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href","#"));
        var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;").attr("href","#"));

        if(!result.extendMap.pageInfo.hasPreviousPage){
            firstPageLi.addClass("disabled");
            prePageLi.addClass("disabled");
        }else{
            //添加点击事件
            firstPageLi.click(function () {
                goToPage(1);
            });
            prePageLi.click(function () {
                goToPage(result.extendMap.pageInfo.pageNum - 1);
            });
        }
        ul.append(firstPageLi).append(prePageLi);

        var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;").attr("href","#"));
        var lastPageLi = $("<li></li>").append($("<a></a>").append("尾页").attr("href","#"));

        if(!result.extendMap.pageInfo.hasNextPage){
            nextPageLi.addClass("disabled");
            lastPageLi.addClass("disabled");
        }else{
            lastPageLi.click(function () {
                goToPage(result.extendMap.pageInfo.pages)
            });
            nextPageLi.click(function () {
                goToPage(result.extendMap.pageInfo.pageNum + 1);
            });
        }

        var pageNum = result.extendMap.pageInfo.pageNum;

        var navigatepageNums = result.extendMap.pageInfo.navigatepageNums;
        $.each(navigatepageNums,function (index,item) {
            var numLi = $("<li></li>").append($("<a></a>").append(item).attr("href","#"));
            if(item == pageNum){
                numLi.addClass("active");
            }
            //添加点击事件
            numLi.click(function () {
                goToPage(item);
            });
            ul.append(numLi);
        });

        ul.append(nextPageLi).append(lastPageLi);

        //把ul添加到nav
        var nav = $("<nav></nav>").append(ul);
        $("#navInfo").append(nav);
    }

    //清空表单
    function clearForm(elemt){
        //清空表单中的数据
        $(elemt).find("*").removeClass("has-error has-success");
        $(elemt).find(".form-control-feedback").removeClass("glyphicon glyphicon-remove glyphicon-ok");
        $(elemt).find(".help-block").text("");
        //清空表单内容
        $(elemt)[0].reset();
    }

    function getDepts(elemt) {
        $(elemt).empty();//清除之前的内容
        $.ajax({
            url: "${APP_PATH}/getAllDepts",
            type: "GET",
            success: function (result) {
//                console.log(result);
                $.each(result.extendMap.deptInfo, function () {
                    var option = $("<option></option>").append(this.deptName).attr("value", this.deptId);
                    option.appendTo(elemt);
                })
            }
        });
    }

    // 添加员工模态框函数
    $("#addEmpBtn").click(function () {
        //清空内容
       clearForm($("#addEmpModal form"));
        //获取下拉框的参数，通过发送ajax请求从数据库中查询
        getDepts("#dept_select");

        //弹出模态框
        $("#addEmpModal").modal({
            backdrop: "static"
        });
    });

    //校验输入框
    function vaildatForm(){
        var empName = $("#empName_input").val();
        var regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5}$)/;
        if(!regName.test(empName)){
            addVaildtionInfo("#empName_input","error","用户名6-16位由数字和字母构成，或者由2-5位汉字构成");
            return false;
        }else{
            addVaildtionInfo("#empName_input","success","");
        }
        var email = $("#email_input").val();
        var regEmail = /^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)+$/;
        if(!regEmail.test(email)){
            addVaildtionInfo("#email_input","error","邮箱格式不正确");
            return false;
        }else{
            addVaildtionInfo("#email_input","success","");
        }
        return true;
    }

    function addVaildtionInfo(elemt,state,message){
        if("error" == state){
            $(elemt).parent().removeClass("has-error has-success");
            $(elemt).parent().addClass("has-error");
            $(elemt).next("span").removeClass("glyphicon glyphicon-remove glyphicon-ok");
            $(elemt).next("span").addClass("glyphicon glyphicon-remove");
            $(elemt).next("span").next("span").text(message);
        }else if("success" == state) {
            $(elemt).parent().removeClass("has-error has-success");
            $(elemt).parent().addClass("has-success");
            $(elemt).next("span").removeClass("glyphicon glyphicon-remove glyphicon-ok");
            $(elemt).next("span").addClass("glyphicon glyphicon-ok");
            $(elemt).next("span").next("span").text(message);
        }
    }

    //校验用户名是否可用
    $("#empName_input").change(function(){
        var empName = this.value ;
        //发送ajax请求
        $.ajax({
            url : "${APP_PATH}/checkEmployee",
            data : "empName=" + empName,
            success : function (result) {
                if(result.returnCode == 1){
                    addVaildtionInfo("#empName_input","success","");
                    $("#saveEmployee_btn").attr("vailInfo","success");
                }else if(result.returnCode == 0){
                    addVaildtionInfo("#empName_input","error",result.extendMap.vailInfo);
                    $("#saveEmployee_btn").attr("vailInfo","error");
                }else{
                    addVaildtionInfo("#empName_input","error",result.extendMap.vailInfo);
                    $("#saveEmployee_btn").attr("vailInfo","error");
                }
            }
        })
    });

    //保存按钮的点击事件
    $("#saveEmployee_btn").click(function(){
        //1.校验输入框中的内容是否合法
        if(!vaildatForm()){
            return false;
        }

        if($(this).attr("vailInfo") == "error"){
            addVaildtionInfo("#empName_input","error","用户名已存在！");
            return false;
        }

        //2.发送ajax请求保存员工信息
        $.ajax({
            url : "${APP_PATH}/saveEmployee",
            type : "POST",
            data : $("#addEmpModal form").serialize(),
            success:function (result) {
               // alert(result.msg);
                //1.保存后关闭模态框
                if(result.returnCode == 1){
                    $("#addEmpModal").modal("hide");
                    //2.跳转到最后一页
                    goToPage(totalPage);
                }else if(result.returnCode == 0){
                   if(result.extendMap.errorMap.email != undefined){
                       addVaildtionInfo("#email_input","error",result.extendMap.errorMap.email);
                   }
                }
            }
        })
    });

    //编辑按钮的点击事件
    $(document).on("click",".update-btn",function(){
        getDepts("#dept_update_select");

        //1.查询员工信息填充到模态框中
        getEmpById($(this).attr("empId"));

        //将员工的id绑定到更新的保存按钮上
        $("#updateEmployee_btn").attr("empId",$(this).attr("empId"));

        //2.弹出模态框
        $("#updateEmpModal").modal({
            backdrop: "static"
        });
    });

    //根据id查询员工信息
    function getEmpById(id){
        $.ajax({
            url : "${APP_PATH}/getEmpById/" + id,
            type : "GET",
            success : function (result) {
                //console.log(result);
                var empInfo = result.extendMap.employee;
                $("#updateEmp_p").text(empInfo.empId);
                $("#email_update_input").val(empInfo.email);
                $("#updateEmpModal input[name=gender]").val([empInfo.gender]);
                $("#updateEmpModal select").val([empInfo.dId]);
            }
        });
    }

    //更新后保存按钮的点击事件
    $("#updateEmployee_btn").click(function () {
        //1.电子邮箱进行校验
        var email = $("#email_update_input").val();
        var regEmail = /^[a-z\d]+(\.[a-z\d]+)*@([\da-z](-[\da-z])?)+(\.{1,2}[a-z]+)+$/;
        if(!regEmail.test(email)){
            addVaildtionInfo("#email_update_input","error","邮箱格式不正确");
            return false;
        }else{
            addVaildtionInfo("#email_update_input","success","");
        }

        //2.发送保存更新后信息的ajax请求
        $.ajax({
            url : "${APP_PATH}/updateEmployee/" + $(this).attr("empId"),
            type : "PUT",
            data : $("#updateEmpModal form").serialize(),
            success : function(result){
                //alert("更新成功");
                //1.关闭模态框
                $("#updateEmpModal").modal("hide");
                //2.回到更新的那一页
                goToPage(currentPage);
            }
        })
    })

    //单个删除按钮的功能实现
    $(document).on("click",".delete-btn",function(){
       //1.提醒用户要删除的员工
        var empName = $(this).parents("tr").find(".emp-name").text();
        var empId = $(this).attr("empId");
        if(confirm("确认要删除员工"+empName+"?")){
            $.ajax({
                url : "${APP_PATH}/emp/" + empId,
                type : "DELETE",
                success : function(){
                    alert("删除成功");
                    goToPage(currentPage);
                }
            })
        }
    });

    //全选框的功能
    $("#checkAll").click(function(){
        //dom的原始属性使用prop，自定义的属性可以使用attr
        var checkAllState = $(this).prop("checked");
        $(".check-item").prop("checked",checkAllState);
    });

    //每个单选框的点击事件
    $(document).on("click",".check-item",function(){
       var flag = $(".check-item:checked").length == $(".check-item").length;
        $("#checkAll").prop("checked",flag);
    });

    //批量删除按钮功能实现
    $("#delEmpBtn").click(function(){
        var empNameList = "";
        var empIdList = "";
        $.each($(".check-item:checked"),function(){
            var empName = $(this).parents("tr").find(".emp-name").text();
            var empId = $(this).parents("tr").find(".emp-id").text();
            empNameList += empName + ",";
            empIdList += empId + "-";
        });

        var empNames = empNameList.substring(0,empNameList.length - 1);
        var empIds = empIdList.substring(0,empIdList.length - 1);
        if(confirm("确定要删除"+empNames+"?")){
            $.ajax({
                url : "${APP_PATH}/emp/" + empIds,
                type : "DELETE",
                success : function(){
                    alert("删除成功！");
                    goToPage(currentPage);
                }
            })
        }

    });
</script>
</body>
</html>
